﻿/// <reference path="jquery-1.8.2.min.js" />
/// <reference path="animation.js" />
/// <reference path="site.js" />

function DataTemplate(params) {
    this.content = null;//params.value;
    this.uri = params.uri;
    this.loaded = false;//((this.content && this.content != "undefined" && this.uri == "undefined"));

    if (typeof DataTemplate.initialized == "undefined") {
        
        // Creates the data template content from uri
        DataTemplate.prototype.Build = function () {
            this.loaded = false;
            var that = this;
            $.ajax({ url: this.uri, success: function (data) {
                that.content = data;
                that.loaded = true;
                site.templating.SynchronizeLoaded();
            } 
            });
        },

        // Fabrics a new instance
        DataTemplate.prototype.LoadContent = function (dataContext) {
            if (this.content && this.loaded) {

                // Initialize variables
                var path = null;
                var value = null;
                var currentBinding = null;
                var contentLoaded = this.content;

                // Recovering binding markups matching with "@{binding path}"
                var bindings = this.content.match(/\@\{set ([^@{}]*)\}/g);
                try {
                    for (var binding in bindings) {
                        currentBinding = bindings[binding];
                        path = currentBinding.replace("@{set", "").replace("}", "").trim().split(".");
                        value = dataContext;
                        for (var varItem in path) {
                            value = value[path[varItem]];
                        }

                        contentLoaded = contentLoaded.replace(currentBinding, value);
                    }

                    return contentLoaded;
                }
                catch (e) {
                    console.error("error one binding " + currentBinding + ": " + e);
                    return null;
                }
            } else {
                return null;
            }
        };

        DataTemplate.initialized = true;
    }
};

site.templating = {
    templates: {},
    onload: null, // callbackFunction
    loaded: false,
    SynchronizeLoaded: function () {
        var loaded = true;
        for (var template in site.templating.templates) {
            loaded &= site.templating.templates[template].loaded;
        }

        if (loaded && !site.templating.loaded) {
            site.templating.loaded = true;
            if (site.templating.onload != null) {
                site.templating.onload();
            }
        } else {
            site.templating.loaded = loaded;
        } 

    }
}